package com.copa.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.copa.dao.NewsDao;
import com.copa.entity.News;
import com.copa.provider.news.BaiduTopNews;
import com.copa.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Objects;

/**
 * @author copa
 * @createDate 2022-02-24 22:51
 * @function
 */
@Service
public class NewsServiceImpl implements NewsService {

    @Autowired
    private NewsDao newsDao;

    @Autowired
    private BaiduTopNews baiduTopNews;

    @Override
    public void insert(News news) {
        newsDao.insert(news);
    }

    @Override
    public News getNewsById(Integer topNum) {
        QueryWrapper<News> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("top_num", topNum)
                .eq("time", LocalDate.now());
        News news = newsDao.selectOne(queryWrapper);
        if (Objects.isNull(news)) {
            baiduTopNews.getNews();
            news = newsDao.selectOne(queryWrapper);
        }
        return news;
    }

    @Override
    public List<News> getDayNews() {
        QueryWrapper<News> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("time", LocalDate.now())
                .orderByAsc("top_num");
        List<News> newsList = newsDao.selectList(queryWrapper);
        if (Objects.isNull(newsList) || newsList.isEmpty()) {
            baiduTopNews.getNews();
            newsList = newsDao.selectList(queryWrapper);
        }
        return newsList;
    }
}
